package org.jianfa.homework.code.controller;

import org.apache.dubbo.config.annotation.Reference;
import org.jianfa.homework.api.MailSerivce;
import org.jianfa.homework.code.service.InternalCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController("/code")
public class CodeController {

    @Autowired
    private InternalCodeService internalCodeService;

    @Reference
    private MailSerivce mailSerivce;

    /**
     * 生成验证码并发送到对应邮箱，成功true，失败false
     *
     * @param email
     * @return
     */
    @PostMapping("/code/create")
    public boolean create(@RequestParam("email") String email) {

        //生成验证码
        String code = internalCodeService.generateRandomCode();

        //保存验证码
        boolean insert = internalCodeService.saveCode(email, code);
        if (!insert) {
            return false;
        }

        //发送验证码
        boolean sendMail = mailSerivce.sendMail(email, code);

        return sendMail;
    }
}
